package com.danciyixue.boot.dcyx.controller;

import com.danciyixue.boot.common.result.Result;
import com.danciyixue.boot.dcyx.model.entity.TaskAssignmentItem;
import com.danciyixue.boot.dcyx.model.form.TaskAssignForm;
import com.danciyixue.boot.dcyx.model.query.TaskMatrixQuery;
import com.danciyixue.boot.dcyx.service.TaskAssignmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@Tag(name = "任务发布(管理端)")
@RestController
@RequestMapping("/api/v1/task-assignments")
@RequiredArgsConstructor
public class TaskAssignmentsController {

    private final TaskAssignmentService taskAssignmentService;

    @Operation(summary = "发布任务（幂等）")
    @PostMapping("/assign")
    @PreAuthorize("@ss.hasPerm('dcyx:task-assignments:assign')")
    public Result<Void> assign(@RequestBody @Valid TaskAssignForm form) {
        boolean ok = taskAssignmentService.assign(form);
        return Result.judge(ok);
    }

    @Operation(summary = "任务矩阵(学生×日期)")
    @GetMapping("/matrix")
    @PreAuthorize("@ss.hasPerm('dcyx:task-assignments:query')")
    public Result<Map<Long, Map<LocalDate, List<TaskAssignmentItem>>>> matrix(TaskMatrixQuery query) {
        return Result.success(taskAssignmentService.getMatrix(query));
    }

    @Operation(summary = "编辑任务子项（仅通关分数）")
    @PutMapping("/item/{id}")
    @PreAuthorize("@ss.hasPerm('dcyx:task-assignments:edit')")
    public Result<Void> updateItem(@PathVariable("id") Long id, @RequestParam("passScore") Integer passScore) {
        boolean ok = taskAssignmentService.updateItemPassScore(id, passScore);
        return Result.judge(ok);
    }

    @Operation(summary = "删除任务子项")
    @DeleteMapping("/item/{id}")
    @PreAuthorize("@ss.hasPerm('dcyx:task-assignments:delete')")
    public Result<Void> deleteItem(@PathVariable("id") Long id) {
        boolean ok = taskAssignmentService.deleteItem(id);
        return Result.judge(ok);
    }

    @Operation(summary = "导出当日任务明细CSV")
    @GetMapping(value = "/export", produces = "text/csv")
    @PreAuthorize("@ss.hasPerm('dcyx:task-assignments:query')")
    public ResponseEntity<String> exportCsv(@RequestParam("targetDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate targetDate) {
        List<TaskAssignmentItem> items = taskAssignmentService.listItemsByDate(targetDate);
        StringBuilder sb = new StringBuilder();
        sb.append("id,studentId,targetDate,unitId,passScore,status,score,completedAt\n");
        for (TaskAssignmentItem it : items) {
            sb.append(it.getId()).append(',')
              .append(it.getStudentId()).append(',')
              .append(targetDate).append(',')
              .append(it.getUnitId()).append(',')
              .append(it.getPassScore() == null ? "" : it.getPassScore()).append(',')
              .append(it.getStatus() == null ? "" : it.getStatus()).append(',')
              .append(it.getScore() == null ? "" : it.getScore()).append(',')
              .append(it.getCompletedAt() == null ? "" : it.getCompletedAt()).append('\n');
        }
        String filename = "task-items-" + targetDate + ".csv";
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                .contentType(MediaType.parseMediaType("text/csv; charset=UTF-8"))
                .body(sb.toString());
    }
}
